/**
 * 
 */
package com.et114.components.image;

/*
 * @author guanhw
 */
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import com.et114.core.utility.Sentence;

/*
<servlet>  
<servlet-name>image</servlet-name>  
<servlet-class>com.et114.components.image.ImageResizer</servlet-class>  
<load-on-startup>1</load-on-startup>  
</servlet>  
<servlet-mapping>  
<servlet-name>image</servlet-name>  
<url-pattern>/image</url-pattern>  
</servlet-mapping>  

<IMG src="/image?root=/albums&file=/thumbs/imagename.jpg&width=270&height=100">  
<IMG src="/image?file=/thumbs/imagename.jpg&width=270 ">
*/  
public class ImageResizer extends HttpServlet {
	protected Log logger = LogFactory.getLog( this.getClass( ) );
	private static final long	serialVersionUID	= - 8285774993751841288L;
	
	public void doGet ( HttpServletRequest request ,
			HttpServletResponse response ) {
		// Optional: Only supports output of jpg and png, defaults to png if not
		// specified
		String imageOutput = getParam ( request , "output" , "png" );
		// Optional: Folder in web app where images are located, defaults to
		// albums if not specified
		String imageRoot = getParam ( request , "root" , "" );
		// Required: Path from root to image, including filename
		String imageFile = getParam ( request , "file" , "" );
		// Required: Width image should be resized to
		int width = Integer.parseInt ( getParam ( request , "width" , "250" ) );
		// Optional: If specified used, otherwise proportions are calculated
		int height = Integer.parseInt ( getParam ( request , "width" , "0" ) );
		
		// Set the mime type of the image
		if ( "png".equals ( imageOutput ) || imageFile.endsWith ( ".png" ) )
			response.setContentType ( "image/png" );
		else
			response.setContentType ( "image/jpeg" );
		
		
		long ct = System.currentTimeMillis ( ) ; 
		// Server Location of the image
		String imageLoc = request.getSession ( ).getServletContext ( )
				.getRealPath ( imageRoot )
				+ imageFile;
		imageLoc = Sentence.replace( imageLoc , 0 , "/", File.separator , Sentence.IGNORE_CASE ) ;
		imageLoc = Sentence.replace( imageLoc , 0 , "\\", File.separator , Sentence.IGNORE_CASE ) ;
		
		
		File imageLocFile = new File ( imageLoc ) ; 
		
		if ( ! imageLocFile.exists ( ) || ! imageLocFile.canRead ( ) || !imageLocFile.isFile ( ) ) {
			String defaultImage = getInitParameter ( "defaultImage" );
			if ( ! StringUtils.isEmpty ( defaultImage )
					&& ! StringUtils.isBlank ( defaultImage ) ) {
				defaultImage = request.getSession ( ).getServletContext ( )
						.getRealPath ( imageRoot )+ defaultImage;
				imageLoc = Sentence.replace ( defaultImage , 0 , "/" ,
						File.separator , Sentence.IGNORE_CASE );
				imageLoc = Sentence.replace ( defaultImage , 0 , "\\" ,
						File.separator , Sentence.IGNORE_CASE );
				imageLocFile = new File ( defaultImage );
			} else
				return;
		}
		
				
		try {
			// Read the original image from the Server Location
			BufferedImage bufferedImage = ImageIO.read ( imageLocFile );
			// Calculate the new Height if not specified
			int calcHeight = height > 0 ? height : ( width
					* bufferedImage.getHeight ( ) / bufferedImage.getWidth ( ) );
			// Write the image
			ImageIO.write ( createResizedCopy ( bufferedImage , width ,
					calcHeight ) , imageOutput , response.getOutputStream ( ) );
		} catch ( Exception e ) {
			e.printStackTrace ( ) ;
			log ( "Problem with image: " + imageLoc + e );
		}
		finally {
			if ( imageLocFile != null ) imageLocFile = null ;
			logger.info ( "Read Image time:" + ( System.currentTimeMillis ( ) - ct ) ) ;
		}
	}
	
	BufferedImage createResizedCopy ( Image originalImage , int scaledWidth ,
			int scaledHeight ) {
		BufferedImage scaledBI = new BufferedImage ( scaledWidth ,
				scaledHeight , BufferedImage.TYPE_INT_RGB );
		Graphics2D g = scaledBI.createGraphics ( );
		g.setComposite ( AlphaComposite.Src );
		g.drawImage ( originalImage , 0 , 0 , scaledWidth ,
						scaledHeight , null );
		g.dispose ( );
		return scaledBI;
	}
	
	// Check the param if it's not present return the default
	private String getParam ( HttpServletRequest request , String param ,
			String def ) {
		String parameter = request.getParameter ( param );
		if ( parameter == null || "".equals ( parameter ) ) {
			return def;
		} else {
			return parameter;
		}
	}
}

/*
public class ImageResizer extends HttpServlet {
	
	private static final long	serialVersionUID	= - 8285774993751841288L;
	
	public void doGet ( HttpServletRequest request ,
			HttpServletResponse response ) {
		// Optional: Only supports output of jpg and png, defaults to png if not
		// specified
		String imageOutput = getParam ( request , "output" , "png" );
		// Optional: Folder in web app where images are located, defaults to
		// albums if not specified
		String imageRoot = getParam ( request , "root" , "" );
		// Required: Path from root to image, including filename
		String imageFile = getParam ( request , "file" , "" );
		// Required: Width image should be resized to
		int width = Integer.parseInt ( getParam ( request , "width" , "250" ) );
		// Optional: If specified used, otherwise proportions are calculated
		int height = Integer.parseInt ( getParam ( request , "height" , "0" ) );
		
		// Set the mime type of the image
		if ( "png".equals ( imageOutput ) )
			response.setContentType ( "image/png" );
		else
			response.setContentType ( "image/jpeg" );
		
		// Server Location of the image
		String imageLoc = request.getSession ( ).getServletContext ( )
				.getRealPath ( imageRoot )
				+ imageFile;
		
		imageLoc = Sentence.replace( imageLoc , 0 , "/", File.separator , Sentence.IGNORE_CASE ) ;
		imageLoc = Sentence.replace( imageLoc , 0 , "\\", File.separator , Sentence.IGNORE_CASE ) ;
		
		BufferedImage bufferedImage = null ; 
		java.io.OutputStream os = null ; 
		File file = null ; 
		try {
			// Read the original image from the Server Location
			file = new File ( imageLoc ) ; 
			bufferedImage = ImageIO.read ( file );
			// Calculate the new Height if not specified
			if ( width > bufferedImage.getWidth ( ) ) 
				width = bufferedImage.getWidth ( ) ; 
			
			int calcHeight = height ; 
			
			if ( calcHeight > bufferedImage.getHeight ( )  ) 
				calcHeight = bufferedImage.getHeight ( )  ;
			else 
			 calcHeight = height > 0 ? height : ( width
					* bufferedImage.getHeight ( ) / bufferedImage.getWidth ( ) );
			// Write the image
			os  =  response.getOutputStream ( ) ;
			ImageIO.write ( createResizedCopy ( bufferedImage ,
					( ( width > bufferedImage.getWidth ( ) ) ? bufferedImage
							.getWidth ( ) : width ) , calcHeight ) ,
					imageOutput , os );
			os.flush ( ) ; 
			os.close ( ) ;
			
	} catch ( Exception e ) {
		e.printStackTrace ( ) ;
			log ( "Problem with image: " + imageLoc + e );
		}
		finally {
			if ( file != null ) file = null ;
			if ( bufferedImage != null ) bufferedImage.flush ( ) ;
			try {
				if ( os != null ) {
					os.flush ( ) ;
					os.close ( ) ;
				}
			}catch ( Exception exx ) {
				exx.printStackTrace ( ) ; 
			} 
			
		}
	}
	
	BufferedImage createResizedCopy ( Image originalImage , int scaledWidth ,
			int scaledHeight ) {
		BufferedImage scaledBI = new BufferedImage ( scaledWidth ,
				scaledHeight , BufferedImage.TYPE_INT_RGB );
		Graphics2D g = scaledBI.createGraphics ( );
		g.setComposite ( AlphaComposite.Src );
		g.drawImage ( originalImage , 0 , 0 , scaledWidth ,
						scaledHeight , null );
		g.dispose ( );
		return scaledBI;
	}
	
	// Check the param if it's not present return the default
	private String getParam ( HttpServletRequest request , String param ,
			String def ) {
		String parameter = request.getParameter ( param );
		if ( parameter == null || "".equals ( parameter ) ) {
			return def;
		} else {
			return parameter;
		}
	}
} */

